var videos = [[]];
var videoIdColIndex = 7;

function playVideo(videoId){
	var indexPath = location.href;
	var rootPath = indexPath.substr(0,indexPath.indexOf('index.php'));
	location.href = rootPath+"playvideo.php?videoId="+videoId;
}

function pageselectCallback(page_index, jq){
	var items_per_page = 5;
	
    // Get number of elements per pagionation page from form
    var max_elem = Math.min((page_index+1) * items_per_page, videos.length);
    var newcontent = '';

    // Iterate through a selection of the content and build an HTML string
    for(var i = page_index*items_per_page; i < max_elem; i++)
    {
        //render videos from response.
        newcontent += "<div class='episoded'>"; 
       	newcontent += "<div class='episodet'><a class='adspruce-streamlink' "
       					+ "type='video/mp4' title='Episode 4' style='cursor:pointer;' onclick='playVideo("+ videos[i]["Id"] +")'>"
       					+ "<img src='"
       					+ videos[i]["ImageLink"]
       					+ "' alt='Episode 4' border='0'></a></div>";
      	newcontent += "<div class='descriptiond'><p class='descriptionp'>"
      					+ videos[i]["Name"]
      					+ "</p>";
      	newcontent += "</div>";
       	newcontent += "<div style='clear: both;'></div>";
    	newcontent += "</div>";
    }

    // Replace old content with new content
    $('#myVideoLinkDiv').html(newcontent);

    // Prevent click eventpropagation
    return false;
}

function getOptionsFromForm(){
    var opt = 
    {
    	callback: pageselectCallback,
    	items_per_page: 5,
    	num_display_entries: 10,
    	num_edge_entries: 2,
    	prev_text: "Prev",
    	next_text: "Next" 
    };
    
    // Avoid html injections in this demo
    var htmlspecialchars ={ "&":"&amp;", "<":"&lt;", ">":"&gt;", '"':"&quot;"};
    $.each(htmlspecialchars, function(k,v){
        opt.prev_text = opt.prev_text.replace(k,v);
        opt.next_text = opt.next_text.replace(k,v);
    });
    return opt;
}

// When document has loaded, initialize pagination and form
$(document).ready(function(){
	$.ajax({
		url : 'Controllers/HomeController.php',
		datatype: 'json',
		type: 'post',
		data: {'action': 'loadvideos'},
		success: function(resp,status){	
			videos = JSON.parse(resp);
			
			if(videos != 'undefined'){
			    var optInit = getOptionsFromForm();
			    $("#Pagination").pagination(videos.length, optInit);
		    }	
		},
		error:function(XMLHttpRequest, textStatus, errorThrown){
			console.log(XMLHttpRequest);
		}
	});
});